﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CheckNameProject
{
    public partial class Checkname : System.Web.UI.Page
    {
        private static bool flag; //For validate javascript
        public static string date;
        static DBNameCheckDataContext db = new DBNameCheckDataContext();
        static List<string> personAutoName = new List<string>();
        private static string DocID;// Keep DocumentID

        protected void Page_Load(object sender, EventArgs e)
        {
            btnDeleteFile.Attributes.Add("OnClick", "return confirm('ต้องการลบไฟล์?');");
            DocID = Request.QueryString["ID"];
            if (!Page.IsPostBack)
            {
                #region CheckDate(love)
                
                try
                {
                    var q = (from p in db.Documents
                             where p.DocumentID == int.Parse(DocID)
                             select p).First();

                    lbtnDocName.Text = q.DocumentName;
                    

                    if (q.Date > DateTime.Now)
                    {
                            lblStatus.ForeColor = System.Drawing.Color.Red;
                            lblStatus.Text = "ยังไม่สามารถที่จะตรวจสอบบุคลากรที่เข้าร่วมการประชุมได้";
                            GridView1.Columns[1].Visible = false;
                            GridView1.Columns[2].Visible = false;
                            btnSave.Visible = false;
                    }
                    else
                    {
                        lblStatus.ForeColor = System.Drawing.Color.Blue;
                        lblStatus.Text = "สามารถที่จะตรวจสอบบุคลากรที่เข้าร่วมการประชุมได้";
                        btnSave.Visible = true;
                    }
                }
                catch (Exception)
                {
                    Response.Redirect("~/Default.aspx");
                }
                #endregion

                #region CheckFile(love)
                var o = (from p in db.Documents
                         where p.DocumentID == int.Parse(DocID)
                         select p.Path).Single();
                if (o!=null)
                {
                    FileInfo file = new FileInfo(o);
                    lblFile.Text = file.Name;
                    btnUpload.Enabled = false;
                    panFile.Visible = true;
                }
                #endregion
            }
            
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            //Insert new person to DB
            Person p = new Person();
            p.FirstName = txtFirstname.Text;
            p.LastName = txtLastname.Text;
            p.FacultyID = int.Parse(cbFact.SelectedValue);
            p.DepartmentID = int.Parse(cbDep.SelectedValue);
            p.PositionID = int.Parse(cbPos.SelectedValue);
            db.Persons.InsertOnSubmit(p);
            db.SubmitChanges();

            //Set new person to this document
            Status s = new Status();
            s.DocumentID = int.Parse(DocID);
            s.PersonID = p.PersonID;
            s.Status1 = true;
            db.Status.InsertOnSubmit(s);
            db.SubmitChanges();

            //Java Script for alert submitcomplete
            StringBuilder sb = new StringBuilder();
            sb = new StringBuilder();
            sb.Append("<script language='javascript' type='text/javascript'>");
            sb.Append("alert('เพิ่มอาจารย์/บุคลากร เรียบร้อยแล้ว!!!')");
            sb.Append("</script>");
            Response.Write(sb.ToString());

            Server.Transfer(Request.FilePath);
        }

        #region Autocomplete txtPersonName

        [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
        public static string[] GetCompletionList(string prefixText, int count, string contextKey)
        {

            var w = from p in db.Persons
                    select p.FirstName + " " + p.LastName;
            personAutoName = w.ToList();
            string[] movies2 = personAutoName.ToArray();
            
            // Return matching movies  
            return (from m in movies2 where m.StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase) select m).Take(count).ToArray();
        }

        #endregion

        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            string[] Name = txtPersonName.Text.Split(' ');

            #region Check name
            
            try
            {
                var q = (from p in db.Persons
                         where p.FirstName == Name[0] && p.LastName == Name[1]
                         select p.PersonID).Single();

                var qDepent = from p in db.Status
                              where p.PersonID == q && p.DocumentID == int.Parse(DocID)
                               select p;

                int x = qDepent.ToList().Count;

                if (x == 0)
                {
                    //Set new person to this document
                    Status s = new Status();
                    s.DocumentID = int.Parse(DocID);
                    s.PersonID = q;
                    s.Status1 = true;

                    db.Status.InsertOnSubmit(s);
                    db.SubmitChanges();
                    flag = true;
                    Server.Transfer(Request.FilePath);
                }
                else
                {
                    //Javascript for not have person
                    StringBuilder sb = new StringBuilder();
                    sb = new StringBuilder();
                    sb.Append("<script language='javascript' type='text/javascript'>");
                    sb.Append("alert('รายชื่อนี้ ได้ถูกใช้งานไปแล้ว!!!')");
                    sb.Append("</script>");
                    Response.Write(sb.ToString());
                    txtPersonName.Text = "";
                    flag = true;
                }

            }
            catch (Exception)
            {
                flag = false;
            }
            #endregion

            #region If name not have
            if (flag == false)
            {
                //Javascript for not have person
                StringBuilder sb = new StringBuilder();
                sb = new StringBuilder();
                sb.Append("<script language='javascript' type='text/javascript'>");
                sb.Append("alert('อาจารย์/บุคลากร ท่านนี้ไม่มีรายชื่อในข้อมูล  กรุณาเพิ่มที่แท็ป เพิ่มรายชื่ออาจารย์/บุคลากร!!!')");
                sb.Append("</script>");
                Response.Write(sb.ToString());

                //Show add tab and set name/lastname in textbox
                try
                {

                    TabContainer1.ActiveTabIndex = 1;
                    txtFirstname.Text = Name[0];
                    txtLastname.Text = Name[1];

                    flag = true;
                }
                catch (Exception)
                {
                }
            }
            #endregion

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox Checkbox_Name = (CheckBox)GridView1.Rows[i].Cells[1].FindControl("chkJoin");
                DropDownList Cause = (DropDownList)GridView1.Rows[i].Cells[2].FindControl("cbCause");
                if (!Checkbox_Name.Checked)
                {
                    HiddenField HD = (HiddenField)(GridView1.Rows[i].FindControl("HiddenField1"));
                    int PersonID = int.Parse(HD.Value);

                    var q = (from p in db.Status
                            where p.DocumentID == int.Parse(DocID) && p.PersonID == PersonID
                            select p).First();
                    q.Status1 = false;
                    q.CauseID = int.Parse(Cause.SelectedValue);
                    db.SubmitChanges();
                }
            }
            var qDocComplete = (from p in db.Documents
                     where p.DocumentID == int.Parse(DocID) 
                     select p).First();
            qDocComplete.StatusID = 1;
            db.SubmitChanges();

        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            HiddenField HD = (HiddenField)(GridView1.Rows[e.RowIndex].FindControl("HiddenField1"));
            int PersonID = int.Parse(HD.Value);

            var q = from p in db.Status
                    where p.DocumentID == int.Parse(Request.QueryString["ID"]) && p.PersonID == PersonID
                    select p;

            db.Status.DeleteAllOnSubmit(q.ToList());
            db.SubmitChanges();

            Server.Transfer(Request.FilePath);
        }

        protected void lbtnDocName_Click(object sender, EventArgs e)
        {
            //Download file in directory.
            var q = (from p in db.Documents
                     where p.DocumentID == int.Parse(DocID)
                     select p).Single();
            if (q.Path!=null)
            {
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment;filename=\"" + q.DocumentName + "\"");
                Response.TransmitFile(q.Path);
                Response.End(); 
            }
            else
            {
                //If document isn't have file.
                StringBuilder sb = new StringBuilder();
                sb = new StringBuilder();
                sb.Append("<script language='javascript' type='text/javascript'>");
                sb.Append("alert('คำสั่งนี้ยังไม่มีไฟล์ให้ดาวโหลด! กรุณาอัพโหลดก่อน')");
                sb.Append("</script>");
                Response.Write(sb.ToString());

                TabContainer1.ActiveTabIndex = 2;
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            //Upload file to directory and update path into database.
            if (FileUploadControl.HasFile)
            {
                if (FileUploadControl.PostedFile.ContentType == "application/pdf")
                {
                    string filename = lbtnDocName.Text + ".pdf";
                    FileUploadControl.SaveAs(Server.MapPath("~/Document/") + filename);
                    string path = Server.MapPath("~/Document/") + filename;

                    var q = (from p in db.Documents
                            where p.DocumentID == int.Parse(DocID)
                            select p).Single();
                    q.Path = path;
                    db.SubmitChanges();

                    lblStatUpload.ForeColor = System.Drawing.Color.Blue;
                    lblStatUpload.Text = "อัพโหลดเสร็จเรียบร้อย";
                    btnUpload.Enabled = false;

                    StringBuilder sb = new StringBuilder();
                    sb = new StringBuilder();
                    sb.Append("<script language='javascript' type='text/javascript'>");
                    sb.Append("alert('อัพโหลดเสร็จเรียบร้อย')");
                    sb.Append("</script>");
                    Response.Write(sb.ToString());

                    Server.Transfer(Request.FilePath);
                }
                else
                {
                    lblStatUpload.ForeColor = System.Drawing.Color.Red;
                    lblStatUpload.Text = "กรุณาเลือกเฉพาะไฟล์ PDF เท่านั้น!!!";
                }
            }
            else
            {
                lblStatUpload.ForeColor = System.Drawing.Color.Red;
                lblStatUpload.Text = "กรุณาอัพโหลดไฟล์ใหม่อีกครั้ง!!!";
            }
        }

        protected void btnDeleteFile_Click(object sender, EventArgs e)
        {
            //Delete file and clear path in database.
            var q = (from p in db.Documents
                    where p.DocumentID == int.Parse(DocID)
                    select p).Single();
            if (q.Path != "")
            {
                File.Delete(q.Path);
                q.Path = null;
                db.SubmitChanges();

                //StringBuilder sb = new StringBuilder();
                //sb = new StringBuilder();
                //sb.Append("<script language='javascript' type='text/javascript'>");
                //sb.Append("OnClick('ลบไฟล์เสร็จเรียบร้อย')");
                //sb.Append("</script>");
                //Response.Write(sb.ToString());
                
                Server.Transfer(Request.FilePath);
            }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            ImageButton lnkDelete = (ImageButton)(e.Row.FindControl("ImageButton1"));

            if (lnkDelete != null)
            {

                lnkDelete.Attributes.Add("OnClick", "return confirm('Delete Record?');");
            }
        }

        protected void txtPersonName_TextChanged(object sender, EventArgs e)
        {
            
        }

    }
}